#include "widgetdelegate.h"

#include <QComboBox>

WidgetDelegate::WidgetDelegate(QItemDelegate *parent) : QItemDelegate(parent) {
    this->m_comboBoxList << "";
}

WidgetDelegate::WidgetDelegate(QStringList list, QItemDelegate *parent) :QItemDelegate(parent) {
    this->m_comboBoxList = list;
}

WidgetDelegate::~WidgetDelegate() {

}
// 创建编辑器
QWidget *WidgetDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    // 创建自己需要的控件进行返回
    QComboBox *editor = new QComboBox(parent);

    return editor;
}

// 设置编辑器数据
void WidgetDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const {
    // 将参数editor转换为对应创建的控件，再进行数据初始设置就行
    QComboBox *cob = static_cast<QComboBox *>(editor);
    cob->addItems(m_comboBoxList);
}

// 更新编辑器集合属性
void WidgetDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    // 将编辑器设置为矩形属性
    editor->setGeometry(option.rect);
}

// 设置模型数据
void WidgetDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const {
    QComboBox *comboBox = static_cast<QComboBox *>(editor);	// 类型转换
    // 模型（单元格）显示的数据
    model->setData(index, comboBox->currentText());
}

// 获取索引处的数据返回
QString WidgetDelegate::getCurrentComboBoxData(int index) {
    return this->m_comboBoxList.at(index);
}

// 插入数据
void WidgetDelegate::insertCoBData(QString str) {
    this->m_comboBoxList.append(str);
}

// 移除数据
void WidgetDelegate::removeCobData(QString str) {
    for (int i = 0; i < this->m_comboBoxList.size(); i++) {
        if (str == this->m_comboBoxList[i]) {
            this->m_comboBoxList.removeAt(i);
            return;
        }
    }
}
